/*******************************************************************************
 * Copyright (c) 2010 liw.
 * All rights reserved. 
 * 
 * This file is part of VanBus.
 * 
 *     VanBus is free software: you can redistribute it and/or modify
 *     it under the terms of the GNU General Public License as published by
 *     the Free Software Foundation, either version 3 of the License, or
 *     (at your option) any later version.
 * 
 *     VanBus is distributed in the hope that it will be useful,
 *     but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License for more details.
 * 
 *     You should have received a copy of the GNU General Public License
 *     along with VanBus.  If not, see <http://www.gnu.org/licenses/>.
 * Contributors:
 *     liw - initial API and implementation
 ******************************************************************************/
package org.niclab.vanbus.activity.comp;

import java.util.ArrayList;
import java.util.EnumSet;

import java.util.Iterator;


import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.DialogInterface;
import android.content.DialogInterface.OnClickListener;
import android.util.Log;
import android.widget.ArrayAdapter;


public abstract class MenuDialog<E extends Enum<E>> {
	
	private static final String LOG_TAG="MenuDialog";

	private Activity ownerActivity;

	private ArrayAdapter<E> adapter;

	public MenuDialog(Activity ownerActivity, int textViewResourceId, Class<E> option){
		this.ownerActivity = ownerActivity;

		ArrayList<E> optionList = new ArrayList<E>();
		for(E e:option.getEnumConstants()){
			optionList.add(e);
		}
		
		adapter = new ArrayAdapter<E>(ownerActivity,textViewResourceId, optionList);
	}
	
	public Dialog createMenuDialog(){
		
		
		AlertDialog.Builder menuBuilder = new AlertDialog.Builder(ownerActivity);
		
		menuBuilder.setAdapter(adapter, new OnClickListener() {
			
			@Override
			public void onClick(DialogInterface dialog, int which) {

				E e = adapter.getItem(which);
				onItemSelected(dialog, e);
			}
		});
		
		AlertDialog aDialog = menuBuilder.create();
		decorateMenu(aDialog);
		return aDialog;
		
	}
	
	public void prepareMenuDialog(Dialog dialog, EnumSet<E> availableOptions){
		
		
		AlertDialog aDialog = (AlertDialog) dialog;
		decorateMenu(aDialog);
	
		adapter.clear();

		Iterator<E> itr = availableOptions.iterator();
		while(itr.hasNext()){
			adapter.add(itr.next());
		}
		
		
		
	}
	
	public void onItemSelected(DialogInterface dialog, E selected){
		dialog.dismiss();
		onItemSelected(selected);
		
	};
	
	public abstract void onItemSelected(E selected);
	
	public abstract void decorateMenu(AlertDialog dialog);

}
